package studiodiva.portfolio.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;

import studiodiva.portfolio.client.lib.even.EventFunction;
import studiodiva.portfolio.client.lib.view.LinkButton;
import studiodiva.portfolio.client.lib.view.View;
import studiodiva.portfolio.client.model.HasApplication;
import studiodiva.portfolio.client.model.titles.Page;
import studiodiva.portfolio.client.model.titles.Title;
import studiodiva.portfolio.client.model.titles.Titles;
import studiodiva.portfolio.client.model.titles.Titles.TitleType;

public class TitleButton extends View<LinkButton> {

  interface Binder extends UiBinder<LinkButton, TitleButton> {}

  private static Binder uiBinder = GWT.create(Binder.class);

  private TitleType title;

  public TitleButton() {
    initWidget(uiBinder.createAndBindUi(this));
  }

  public void initialize(HasApplication parent, TitleType title) {
    super.initialize(parent);
    this.title = title;
    initialize(parent);
    getTitles().addHandler(Titles.ON_CHANGE, new EventFunction<Title>() {
      public void run(Title value) {
        updateActive();
      }
    });
    getTitles().getTitle(title).addHandler(Title.ON_PAGE_CHANGE, new EventFunction<Page>() {
      public void run(Page value) {
        updateTarget();
      }
    });
    updateActive();
    updateTarget();
  }

  public void setText(String value) {
    widget().setText(value);
  }

  private Title getTitle() {
    return getTitles().getTitle(title);
  }

  private Titles getTitles() {
    return getApplication().getTitles();
  }

  private void updateActive() {
    widget().setActive(title == getTitles().getState());
  }

  private void updateTarget() {
    widget().setTarget("page=" + getTitle().getPage().getId());
  }
}